<?php
/**
 * 摇号中签数据处理到数据库
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}
require(API_ROOT_PATH . '/../inc/common.php');

function getFileName($file)
{
    return pathinfo($file, PATHINFO_FILENAME);
}

//获取到明天间隔
function getTimeDiff()
{
    $time1 = $date1 = date("Y-m-d H:i:s");
    $time2 = date("Y-m-d 00:00:00", strtotime("+ 1 day"));
    $s = strtotime($time2) - time();
    return $s;
}

$clcwDb = get_clcw_db();
$time = time();

while (true) {
    try {
        //判断数据库链接状态
        if (!$clcwDb->ping()) {
            $clcwDb = get_clcw_db();
        }

        $lotNumberData = $clcwDb->where('status', 1)->orderBy('id', 'DESC')->getOne('lot_number_file');
        if (empty($lotNumberData)) {
            logUtil("lot_number_data no data can be processed,sleep 60s", "INFO");
            sleep(60);
            continue;
        }

        $lotNumberFileName = getFileName($lotNumberData['url']) . '.txt';

        $file_path = API_ROOT_PATH . '/../../Public/Clcw/LotNumber/' . $lotNumberFileName;
        if (!is_file($file_path)) {
            logUtil("File resource does not exist,sleep 60s", "INFO");
            sleep(60);
            continue;
        }
        $string = file_get_contents($file_path);
        $file_data = str_replace(' ', PHP_EOL, $string);
        file_put_contents($file_path, $file_data);
        sleep(30);
        $file = fopen($file_path, 'r');
        $lotnumber = [];
        $i = 1;
        while (!feof($file)) {
            $line = trim(fgets($file));
            if (strlen($line) == 13) {
                $lotnumber[$i] = $line;
                $i++;
            }
        }
        fclose($file);
        $lotnumber = array_filter($lotnumber);
        $lotTotal = count($lotnumber);
        foreach ($lotnumber as $v) {
            $ret = $clcwDb->where('apply_code', $v)->getOne('lot_number_ballot');
            if (!empty($ret)) {
                logUtil("数据重复", "ERROR");
                continue;
            }
            $insertData = [
                'apply_code'  => $v,
                'create_time' => $time
            ];
            $ret1 = $clcwDb->insert('lot_number_ballot', $insertData);
            if ($ret1) {
                logUtil("success, id: {$ret1}, apply_code: {$v}", "INFO");
            } else {
                logUtil("failed, apply_code:{$v}", "ERROR");
            }
        }
        $ret2 = $clcwDb->where('id', $lotNumberData['id'])->update('lot_number_file',
            [
                'total'       => $lotTotal,
                'status'      => 2,
                'update_time' => $time
            ]
        );
        if (!$ret2) {
            logUtil("lot number file failed, id: {$lotNumberData['id']}", "ERR");
        }
        logUtil("lot number file success, id: {$lotNumberData['id']}", "INFO");
    } catch (Exception $e) {
        logUtil($e->getCode() . ": " . $e->getMessage(), "ERROR");
        sleep(60);
    }
}
